/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2023-12-27 10:23:27
 * @Description  : 对node-redis的方法进行了二次封装
 */

const client = require('./index')

module.exports.wpIncreaseHset = async (key, field) => {
  let res = await client.HGET(key, field)
  if (!res) {
    res = 1
  } else {
    res = Number(res)
    res++
  }
  await client.HSET(key, field, res)
  const cnt = await client.HGET(key, field)
  return cnt
}

module.exports.wpHset = async (key, field, value, expired) => {
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }
  await client.HSET(key, field, value)
  if (expired) {
    await client.PEXPIRE(`${key}:${field}`, expired)
  }
}

module.exports.wpHget = async (key, field) => {
  const data = await client.HGET(key, field)
  let res
  try {
    res = JSON.parse(data)
  } catch {
    res = data
  }
  return res
}

module.exports.wpSet = async (key, value, expired) => {
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }
  await client.set(key, value, {
    EX: expired
  })
}

module.exports.wpGet = async (key) => {
  const data = await client.GET(key)
  let res
  try {
    res = JSON.parse(data)
  } catch {
    res = data
  }
  return res
}

module.exports.wpTtl = async (key) => {
  const data = await client.ttl(key)
  return data
}

module.exports.wpDel = async (key) => {
  const data = await client.del(key)
  return data
}
